package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.UUID;

//通用接口

@Slf4j
@RestController
@RequestMapping("/admin/common")
public class CommonController {

    @Autowired
    private AliOssUtil AliOssUtil;


    //文件上传
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file){
        try {
            //获取原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名后缀
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            //拼接新的文件名
            String objecttname = UUID.randomUUID().toString() + suffix;
            //获取文件的请求路径
            String upload = AliOssUtil.upload(file.getBytes(), objecttname);
            //返回文件上传路径
            return Result.success(upload);
        } catch (Exception e) {
            log.error("文件上传失败" ,e);
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
}
